/*
 * Copyright (C) 2008 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.zxing.client.android;

import java.io.IOException;
import java.util.Vector;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.google.zxing.client.android.camera.CameraManager;

import d512a.TAKO.BasketActivity;
import d512a.TAKO.HomescreenActivity;
import d512a.TAKO.ProductTabWidgetActivity;
import d512a.TAKO.R;
import d512a.TAKO.UserInfoActivity;
import d512a.TAKO.helpers.DataBaseHelper;
/**
 * The barcode reader activity itself. This is loosely based on the CameraPreview
 * example included in the Android SDK.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 * @author Sean Owen
 */
public final class CaptureActivity extends Activity implements SurfaceHolder.Callback {

  private static final String TAG = CaptureActivity.class.getSimpleName();

  private DataBaseHelper db;
  private CaptureActivityHandler handler;
  private boolean hasSurface;
  private Vector<BarcodeFormat> decodeFormats;
  private String characterSet;
  private InactivityTimer inactivityTimer;
  private BeepManager beepManager;

  public Handler getHandler() {
    return handler;
  }

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    setContentView(R.layout.capture);

    CameraManager.init(getApplication());
    handler = null;
    hasSurface = false;
    inactivityTimer = new InactivityTimer(this);
    beepManager = new BeepManager(this);

//    showHelpOnFirstLaunch();
  }

  @Override
  protected void onResume() {
    super.onResume();

    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
    SurfaceHolder surfaceHolder = surfaceView.getHolder();
    if (hasSurface) {
      // The activity was paused but not stopped, so the surface still exists. Therefore
      // surfaceCreated() won't be called, so init the camera here.
      initCamera(surfaceHolder);
    } else {
      // Install the callback and wait for surfaceCreated() to init the camera.
      surfaceHolder.addCallback(this);
      surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    Intent intent = getIntent();
    String action = intent == null ? null : intent.getAction();
    if (intent != null && action != null) {
      if (action.equals(Intents.Scan.ACTION)) {
        decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);
      } else {
        decodeFormats = null;
      }
      characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
    } else {
      decodeFormats = null;
      characterSet = null;
    }

    //SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    //prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true);

    beepManager.updatePrefs();
  }

  @Override
  protected void onPause() {
    super.onPause();
    if (handler != null) {
      handler.quitSynchronously();
      handler = null;
    }
    CameraManager.get().closeDriver();
  }

  @Override
  protected void onDestroy() {
    inactivityTimer.shutdown();
    super.onDestroy();
  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        setResult(RESULT_CANCELED);
        finish();
        return true;
    } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
      // Handle these events so they don't launch the Camera app
      return true;
    }
    return super.onKeyDown(keyCode, event);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.menu.camera_menu, menu);
      return true;
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
      // Handle item selection
      Intent i;
      switch (item.getItemId()) {
          case R.id.home:
              i = new Intent(getApplicationContext(), HomescreenActivity.class);
              startActivity(i);
              return true;
          case R.id.basket:
              i = new Intent(getApplicationContext(), BasketActivity.class);
              startActivity(i);
              return true;
          case R.id.settings:
              i = new Intent(getApplicationContext(), UserInfoActivity.class);
              startActivity(i);
            return true;
          default:
              return super.onOptionsItemSelected(item);
      }
  }

  public void surfaceCreated(SurfaceHolder holder) {
    if (!hasSurface) {
      hasSurface = true;
      initCamera(holder);
    }
  }

  public void surfaceDestroyed(SurfaceHolder holder) {
    hasSurface = false;
  }

  public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

  }

  /**
   * A valid barcode has been found, so give an indication of success and show the results.
   *
   * @param rawResult The contents of the barcode.
   */
  public void handleDecode(Result rawResult) {
	  inactivityTimer.onActivity();
	  beepManager.playBeepSoundAndVibrate();
      handleDecodeInternally(rawResult);
  }
  
  // Skift activity til det resultactivity vi vil have
  private void handleDecodeInternally(Result rawResult) {
      db = new DataBaseHelper(getApplicationContext());
      try {
          db.openDataBase();
      } catch (SQLException e) {
          throw e;
      } finally {
          db.close();
      }
      
      String barcode = rawResult.getText();
      try {
          if(db.barcodeExists(barcode, barcode.substring(0, 6))){
              Intent i = new Intent(getApplicationContext(), ProductTabWidgetActivity.class);
              ProductTabWidgetActivity.fromScan = true;
              i.putExtra("barcode", barcode);
              startActivity(i);
              finish();  
          } else {
              Toast.makeText(getApplicationContext(), "Stregkoden kunne ikke findes", Toast.LENGTH_LONG)
              .show();
              
              Intent intent = getIntent();
              finish();
              startActivity(intent);
          }
      } catch (StringIndexOutOfBoundsException e) {
          Log.e("CameraError", "Something terribly wrong");
          Toast.makeText(getApplicationContext(), "Der opstod en fejl.", Toast.LENGTH_LONG)
          .show();
          
          Intent intent = getIntent();
          finish();
          startActivity(intent);
      }
  }

   /**
   * We want the help screen to be shown automatically the first time a new version of the app is
   * run. The easiest way to do this is to check android:versionCode from the manifest, and compare
   * it to a value stored as a preference.
   */
//  private boolean showHelpOnFirstLaunch() {
//    try {
//      PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
//      int currentVersion = info.versionCode;
//      // Since we're paying to talk to the PackageManager anyway, it makes sense to cache the app
//      // version name here for display in the about box later.
//      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
//      int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
//      if (currentVersion > lastVersion) {
//        prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
//        Intent intent = new Intent(this, HelpActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
//        // Show the default page on a clean install, and the what's new page on an upgrade.
//        String page = (lastVersion == 0) ? HelpActivity.DEFAULT_PAGE : HelpActivity.WHATS_NEW_PAGE;
//        intent.putExtra(HelpActivity.REQUESTED_PAGE_KEY, page);
//        startActivity(intent);
//        return true;
//      }
//    } catch (PackageManager.NameNotFoundException e) {
//      Log.w(TAG, e);
//    }
//    return false;
//  }

  private void initCamera(SurfaceHolder surfaceHolder) {
    try {
      CameraManager.get().openDriver(surfaceHolder);
    } catch (IOException ioe) {
      Log.w(TAG, ioe);
      displayFrameworkBugMessageAndExit();
      return;
    } catch (RuntimeException e) {
      // Barcode Scanner has seen crashes in the wild of this variety:
      // java.?lang.?RuntimeException: Fail to connect to camera service
      Log.w(TAG, "Unexpected error initializating camera", e);
      displayFrameworkBugMessageAndExit();
      return;
    }
    if (handler == null) {
      handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
    }
  }

  private void displayFrameworkBugMessageAndExit() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(getString(R.string.app_name));
    builder.setMessage(getString(R.string.msg_camera_framework_bug));
    builder.setPositiveButton(R.string.button_ok, new FinishListener(this));
    builder.setOnCancelListener(new FinishListener(this));
    builder.show();
  }
}
